#!/usr/bin/perl
#
use strict;
use warnings;
use Data::Dumper;
 
binmode STDOUT, ":utf8";
#use utf8;
 
use JSON;
require "doa_subs.pl";
use File::Copy;
use CGI;
use lib '.';
use users;

my ($username,$level) = &validate;


############################## Main Prog ##############################
#
# This program will process all files in the mapdata directory
# Creating/updating mapfile.json with up-to-date player details
#
# terrain:{256,646":[900340313,"Brelm",0,1,0,-1],"256,657":[900366906,"Skyrim",0,1,0,-1]}
# players:{"900315223":[0,4,0,37527,"The Spreading Death",0],"900315225":[0,2,0,5020,0,0]}
#
my $q = new CGI;

print $q->header;
print $q->start_html(
	-title => "Process Map files"
);

print $q->h1("process map update files");
my @mapFiles=readDir("mapdata");
my $data;
my $outdata={};
my $alliance_id={};
my $alliance_name={};
print $q->p("loading Alliance Deatils...");
my $alliance_count=loadAlliance($alliance_id, $alliance_name);
print $q->p("Loaded $alliance_count");

print $q->br();
#print $q->p("Loading existing MAPDATA");
$outdata=readJSON("mapfile.json");
#$print $q->p(".... Loaded");
my $file_count=0;
print $q->p("starting file loop");
foreach my $mapfile (@mapFiles)
{
	my $fullname="mapdata/".$mapfile;
	$data=readJSON($fullname);
	my ($fdate,$ftime,$timestring)=pfileDate($mapfile);
	
	print $q->p("Processing update file $fdate $ftime");
	
	my $scanlref=$data->{'map'}{'scanloc'};
	my $playerref=$data->{'map'}{'players'};
    my $player_count=0;
	my $city_count=0;
	my $outpost_count=0;
	my @dataout;
	($fdate,$ftime,$timestring)=pdateTime($data->{'map'}{'scanlocstart'});
	print $q->p("Scan start time $fdate $ftime");
	($fdate,$ftime,$timestring)=pdateTime($data->{'map'}{'scanlocend'});
	print $q->p("Scan end time $fdate $ftime");

	# if (exists $data->{'map'}{'scanloc'})
	# {
		# print $q->br();
		# print $q->p("contents of update file");
		# print $q->br();
		# my $row_count=0;
		# my $outstring="";
		# foreach my $loc ( @$scanlref)
		# {
			# $outstring+=$q->td($scanlref->{$loc});
			# $row_count++;
			# if ($row_count == 13)
			# {
				# push (@dataout,$outstring);
				# $row_count=0;
				# $outstring="";
			# }
		# }
		# print $q->table({-border=>undef,-width=>'25%'},
			# $q->Tr({ -align => "CENTER", -valign => "TOP" },\@dataout)
		   # );
	# }
	print $q->br();

	foreach my $playerid ( keys %{$playerref})
	{
		my $members={};
		my $might=$playerref->{$playerid}->[3];
		my $alliname=$playerref->{$playerid}->[4];
        my $allid=$alliance_name->{$alliname}||"0";
		my $oldallid=$outdata->{'map'}{$playerid}{'player'}{'allid'}||0;
		$outdata->{'map'}{$playerid}{'player'}={ 'might'=>$might, 'allid'=>$allid, 'ts'=>$timestring };
		$members=$outdata->{'members'}{$allid} if defined $outdata->{'members'}{$allid};
		
		$members->{$playerid}="y";
		# if ( grep { $playerid eq $_ } @$members)
		# {
			# warn("$playerid already in list");
		# }
		# else
		# {
			# push (@$members, $playerid);
		# }
		$outdata->{'members'}{$allid}=$members;
		$player_count++;
		$members=$outdata->{'members'}{$oldallid} if defined $outdata->{'members'}{$oldallid}; # remove player from old alliance 
		delete $members->{$playerid};
		$outdata->{'members'}{$oldallid}=$members;
	}

	my $mapref = $data->{'map'}{'terrain'};
	foreach my $maploc (keys %{$mapref})		# we have the x,y location from the terrain
	{
		my $pid=$mapref->{$maploc}->[0];
		my $cityname=$mapref->{$maploc}->[1];
		my $level=$mapref->{$maploc}->[3];
		if ($cityname =~ "_dragon outpost")
		{
			my $outpost={};
			$outpost=$outdata->{'map'}{$pid}{'outposts'} if defined $outdata->{'map'}{$pid}{'outposts'};
			$outpost_count++;
			$outpost->{$cityname}={'loc'=>$maploc, 'lvl'=>$level, 'ts'=>$timestring };
			$outdata->{'map'}{$pid}{'outposts'}=$outpost;
		}
		else 
		{
			$outdata->{'map'}{$pid}{'city'}={'name'=>$cityname, 'loc'=>$maploc, 'level'=>$level, 'ts'=>$timestring};
			$city_count++;
		}
	}
	print $q->p("processed [$player_count] Players [$city_count] Cities [$outpost_count] Outposts");
	move("$fullname","processed_map/$mapfile") or die_nice ("Could not move $mapfile to processed_map directory");
	$file_count++;
}
print $q->br();
print $q->p("Processed $file_count Map files");

writeJSON($outdata,"mapfile.json");

print $q->br();
print $q->a( {-href=>"menu.cgi"}, "Main Menu");
print $q->end_html;
